﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media.Imaging;

namespace jpgw
{
    public partial class Form1 : Form
    {
        private static System.Timers.Timer aTimer;

        public static int PORT = 2345;
        
        public static int PORT2 = 8765;

        public static string IP = "192.168.0.102";

        public static Bitmap bmp;

        public static int clickX = -1;
        public static int clickY = -1;

        public static Boolean running = false;

        public Thread t;

        public Thread t2;

        public Form1()
        {
            InitializeComponent();

            running = true;
            t = new Thread(update);
            t.Start();

            t2 = new Thread(update2);
            t2.Start();

            // Create a timer with a two second interval.
            aTimer = new System.Timers.Timer(100);
            // Hook up the Elapsed event for the timer. 
            aTimer.Elapsed += OnTimedEvent;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;


        }



        public static BitmapSource ConvertBitmap(Bitmap source)
        {
            return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                          source.GetHbitmap(),
                          IntPtr.Zero,
                          Int32Rect.Empty,
                          BitmapSizeOptions.FromEmptyOptions());
        }

        public static Bitmap BitmapFromSource(BitmapSource bitmapsource)
        {
            Bitmap bitmap;
            using (var outStream = new MemoryStream())
            {
                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(bitmapsource));
                enc.Save(outStream);
                bitmap = new Bitmap(outStream);
            }
            return bitmap;
        }



        static byte[] ToByte(int[] a)
        {
            byte[] bytes = new byte[a.Length*4];

            int j = 0;
            for(int i=0;i<a.Length;i++)
            {
                bytes[j++] = (byte)(a[i]);
                bytes[j++] = (byte)(a[i] >> 8);
                bytes[j++] = (byte)(a[i] >> 16);                
                bytes[j++] = (byte)(a[i] >> 24);
            }
            return bytes;
        }


        static Bitmap decode(byte[] image)
        {
            Stream imageStreamSource = new MemoryStream(image);

            JpegBitmapDecoder decoder = new JpegBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            BitmapSource bitmapSource = decoder.Frames[0];

            return BitmapFromSource(bitmapSource);
        }

        static void rcv()
        {
            Socket ClientSocket;

            //所有UR的控制都在这里完成，先生成一个ClientSocket
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress myIP = IPAddress.Parse(IP);
            IPEndPoint ipe = new IPEndPoint(myIP, PORT);

            Console.WriteLine("in connect");

            //一次连接终生使用
            try
            {
                ClientSocket.Connect(ipe);
            }
            catch (Exception connectError)
            {
                Console.WriteLine(connectError.ToString());
            }



            byte[] bytes = new byte[1024];

            byte[] img = new byte[1024 * 1024]; //allocate 1MB for jpg buffer

            int i = 0;

            Console.WriteLine("in");

            while (true)
            {
                int bytesRec = ClientSocket.Receive(bytes);
                bytes.CopyTo(img, i);
                i += bytesRec;
                if (bytesRec == 0)
                    break;
            }

            Console.WriteLine("i= " + i);

            //ClientSocket.Shutdown(SocketShutdown.Both);
            ClientSocket.Close();


            byte[] imgr = new byte[i];
            Buffer.BlockCopy(img, 0, imgr, 0, i);

            try
            {
                //File.WriteAllBytes("a.jpg", imgr);
                bmp = decode(imgr);
            }
            catch
            {
            }

        }


        static void snd(int a, int b)
        {
            Socket ClientSocket;
            
            //所有UR的控制都在这里完成，先生成一个ClientSocket
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress myIP = IPAddress.Parse(IP);
            IPEndPoint ipe = new IPEndPoint(myIP, PORT2);
            Console.WriteLine("out connect");

            //一次连接终生使用
            try
            {
                ClientSocket.Connect(ipe);
            }
            catch (Exception connectError)
            {
                Console.WriteLine(connectError.ToString());
            }

            int[] aa = new int[8]
            {
                a-20, b-20,
                a-20,b+20,
                a+20,b+20,
                a+20,b-20
            };

            Console.WriteLine("out");

            int byteOut=ClientSocket.Send(ToByte(aa));

            Console.WriteLine("o= " + byteOut);

            //ClientSocket.Shutdown(SocketShutdown.Both);
            ClientSocket.Close();
        }



        static void update()
        {
            while (running)
            {
                rcv();
            }

        }


        static void update2()
        {
            Random rnd = new Random();

            while (running)
            {
                //if (clickX > 0 && clickY > 0)
                {
                    snd(clickX, clickY);
                    //clickX = -1;
                    //clickY = -1;
                }
                //else
                {
                    //Thread.Yield();
                    int ms = rnd.Next(4, 29);
                    Thread.Sleep(ms * 1000);
                }

            }

        }

        private void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            //Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
            //e.SignalTime);

            this.pictureBox1.Image = bmp;
        }



        private void pictureBox1_Click(object sender, EventArgs e)
        {

            clickX = 200;
            clickY = 400;
            //this.pictureBox1.Image = new Bitmap("a.jpg");
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            running = false;
            t.Join();
            //t2.Join();
        }
    }
}
